#   This file is part of Pylot.
#    
#   optionparse is a wrapper around optparse
#   taken from ASPN Python Coockbook
#   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844


import optparse
import re
import sys
import config


USAGE = re.compile(r'(?s)\s*usage: (.*?)(\n[ \t]*\n|$)')

def nonzero(self): # will become the nonzero method of optparse.Values  
    # True if options were given
    for v in self.__dict__.itervalues():
        if v is not None:
            return True
    return False

optparse.Values.__nonzero__ = nonzero # dynamically fix optparse.Values

class ParsingError(Exception): 
    pass

optionstring = ''

def exit(msg=''):
    raise SystemExit(msg or optionstring.replace('%prog', sys.argv[0]))

def parse():
    usage="usage: %prog [options]  args"
    parser=optparse.OptionParser(usage,version=config.VERSION)
    help="nubmer of agents"
    parser.add_option('-a','--agents',
            type=int,default=config.AGENTS,
            metavar='NUM_AGENTS',help=help)

    help="test duration in seconds"
    parser.add_option('-d','--duration',
            type=int,default=config.DURATION,
            metavar='DUARTION',help=help)

    help="rampup in seconds"
    parser.add_option('-r','--rampup',
            type=int,default=config.RAMPUP,
            metavar='RAMPUP',help=help)

    help="interval in milliseconds"
    parser.add_option('-i','--interval',
            type=int,default=config.INTERVAL,
            metavar='INTERVAL',help=help)

    help="test case xml file"
    parser.add_option('-x','--xmlfile',
            default=config.TC_XML_FILENAME,
            metavar='TEST_CASE_XML',help=help)

    help="output directory"
    parser.add_option('-o','--output_dir',dest='output_dir',
            default=config.OUTPUT_DIR,
            metavar='PATH',help=help)
    
    help="name of test"
    parser.add_option('-n','--name',default=config.TEST_NAME,
            metavar='NAME',help=help)

    help="log message"
    parser.add_option('-l','--log_msgs',action='store_true',
            default=config.LOG_MSGS,dest="log_msgs",
            help=help)

    help="blocking mode"
    parser.add_option('-b','--blocking',action='store_true',
            default=config.BLOCKING,help=help)

    help="start GUI"
    parser.add_option('-g','--gui',action='store_true',
            default=config.GUI,help=help)

    help="xml-rpc listening port"
    parser.add_option('-p','--port',
            type=int,help=help)

    help="output debug info"
    parser.add_option('-D','--debug',default=config.HTTP_DEBUG,
            action="store_true",help=help)

    return parser.parse_args()

